<template>
  <lay-card>
    <lay-form :model="link_info" ref="layFormRef4" :rules="rules" width="100px" required>
      <lay-form-item label="连接名" prop="name">
        <lay-input v-model="link_info.name"></lay-input>
      </lay-form-item>
      <lay-form-item label="数据库类型" prop="dataBaseType">
        <lay-input v-model="link_info.dataBaseType" disabled></lay-input>
      </lay-form-item>
      <lay-form-item label="主机" prop="ip">
        <lay-input v-model="link_info.ip"></lay-input>
      </lay-form-item>
      <lay-form-item label="端口" prop="port">
        <lay-input v-model="link_info.port">></lay-input>
      </lay-form-item>
      <lay-form-item :label="database_name">
        <lay-input v-model="link_info.serverName"></lay-input>
      </lay-form-item>
      <lay-form-item label="用户名" prop="userName">
        <lay-input v-model="link_info.userName"></lay-input>
      </lay-form-item>
      <lay-form-item label="密码" prop="passWord">
        <lay-input v-model="link_info.passWord" type="password" allow-clear></lay-input>
      </lay-form-item>
      <lay-form-item label="备注">
        <lay-input v-model="link_info.remark"></lay-input>
      </lay-form-item>
      <lay-form-item style="text-align: center;">
        <lay-button type="normal" @click="linkTestOperate">测试连接</lay-button>
        <lay-button type="normal" @click="addLink">确定</lay-button>
        <lay-button @click="closeMsg">取消</lay-button>
      </lay-form-item>
    </lay-form>
    <div style="max-height: 40px">
      <lay-line></lay-line>
      <span id="error_message" :style="msg_style">{{display_result}}</span>
    </div>
  </lay-card>
</template>

<script lang="ts">
import {onMounted} from "vue";

export default {
  name: "AddDataSource",
};
</script>

<script lang="ts" setup>
import {ref, onMounted, onBeforeMount} from 'vue';
import { layer } from '@layui/layer-vue';
import {addNodeOrLink, getLinkDetail, linkTest, updateLink} from "../../api/module/db";
import {Source} from "../../store/interface/VirtulTreeInterface";
import {notify} from "../../untils/tip";
import {passwordEncryption} from "../../store/user";

// 组件入参
const {operate, currentNode, updateData, closeLayUi} = defineProps({
  operate: {type: String},
  currentNode: {type: Object},
  updateData: {type: Function},
  closeLayUi: {type: Function}
})

// 组件定义的内部应用参数
const updateDataFunction = ref();
const display_result = ref('');
const msg_style = ref('');
const layFormRef4 = ref();
const database_name = ref('');

// 数据库连接信息
const link_info = ref<Source>({
  name: '',
  dataBaseType: 'mysql',
  ip: '',
  port: 0,
  serverName: '',
  userName: '',
  passWord: '',
  remark: ''
})

const rules = ref({
  name: {type: 'string'},
  dataBaseType: {type: 'string'},
  ip: {type: 'string'},
  passWord : {
    type : 'string'
  },
  userName : {
    type :  'string'
  }
})

// 初始化信息
onBeforeMount(() =>{
  updateDataFunction.value = updateData;
  if(currentNode?.data){
    link_info.value = currentNode.data;
  }
  if(operate !== 'add'){link_info.value.passWord = 'OLD_PASSWORD';}
  if(link_info.value.dataBaseType === 'oracle'){
    database_name.value = '实例名'
  }else{
    database_name.value = '库名'
  }
});

// 关闭弹框窗口
const closeMsg = () => {
  if(closeLayUi){
    closeLayUi();
  }else {
    notify('failed', '关闭函数异常！')
  }
};

// 测试连接
const linkTestOperate = () => {
  layFormRef4.value.validate(async (isValidate: boolean, model: object, errors: any) => {
    if(isValidate){
      const link_params = JSON.parse(JSON.stringify(link_info.value))
      if(link_info.value.passWord !== 'OLD_PASSWORD'){
        link_params.passWord = passwordEncryption(link_info.value.passWord);
      }else {
        link_params.passWord = "";
      }
      let {result, status, message} = await linkTest(link_params)
      if(status === 'success'){
        display_result.value = '连接测试成功！';
        msg_style.value = 'color: green';
      }else {
        display_result.value = '失败信息是：' + message;
        msg_style.value = 'color: red';
      }
    }else {
      layer.open({
        type: 1,
        title:"表单校验失败",
        content: `<div style="padding: 10px"><p>是否通过 : ${isValidate}</p><p>表单信息 : ${model}</p><p>错误信息 : ${JSON.stringify(errors)}</p></div>`,
        shade: false,
        isHtmlFragment: true,
        btn : [{ text: '确认', callback(index: bigint) {  layer.close(index) }}],
        area : '500px'
      });
    }
  });
};

const addLink = () => {
  layFormRef4.value.validate(async (isValidate: boolean, model: object, errors: any) => {
    if(isValidate){
      if(currentNode){
        const link_params = JSON.parse(JSON.stringify(link_info.value))
        if(link_info.value.passWord !== 'OLD_PASSWORD'){
          link_params.passWord = passwordEncryption(link_info.value.passWord);
        }else {
          link_params.passWord = "";
        }
        currentNode.data = link_params;    // 关键步骤，更新 子节点 的 数据库连接信息
        currentNode.name = link_info.value.name;  // 更新节点名称
        console.log("addLink node : ", currentNode)
        if(operate === 'add'){
          // 新增连接信息
          let {result, status, message} = await addNodeOrLink(currentNode);
          if(status === 'success'){
            currentNode.id = result.id;   // 更新节点id
            updateDataFunction.value(currentNode);
            display_result.value = message;
            msg_style.value = 'color: green';
          }else {
            display_result.value = message;
            msg_style.value = 'color: red';
          }
        }else {
          // 更新连接信息
          let {result, status, message} = await updateLink(currentNode);
          if(status === 'success'){
            updateDataFunction.value(currentNode);
            display_result.value = message;
            msg_style.value = 'color: green';
          }else {
            layer.msg(message);
            display_result.value = message;
            msg_style.value = 'color: red';
          }
        }
      }else {
        notify('failed', '节点信息为空！')
      }
    }else {
      layer.open({
        type: 1,
        title:"表单校验失败",
        content: `<div style="padding: 10px"><p>是否通过 : ${isValidate}</p><p>错误信息 : ${JSON.stringify(errors)}</p></div>`,
        shade: false,
        isHtmlFragment: true,
        btn : [{ text: '确认', callback(index: bigint) {  layer.close(index) }}],
        area : '500px'
      });
    }
  })
};

</script>

<style>

</style>